package com.example.messengerapp.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.messengerapp.model.AuthResult
import com.example.messengerapp.repository.AuthRepository
import kotlinx.coroutines.launch

class AuthViewModel : ViewModel() {

    private val authRepository = AuthRepository()

    private val _email = MutableLiveData<String>()
    val email: LiveData<String> = _email

    private val _password = MutableLiveData<String>()
    val password: LiveData<String> = _password

    private val _authResult = MutableLiveData<AuthResult?>()
    val authResult: LiveData<AuthResult?> = _authResult

    fun setEmail(emailValue: String) {
        _email.value = emailValue
    }

    fun setPassword(passwordValue: String) {
        _password.value = passwordValue
    }

    fun login() {
        val emailValue = _email.value ?: return
        val passwordValue = _password.value ?: return

        viewModelScope.launch {
            try {
                val result = authRepository.login(emailValue, passwordValue)
                _authResult.value = AuthResult(success = true)
            } catch (e: Exception) {
                _authResult.value = AuthResult(success = false, errorMessage = e.message)
            }
        }
    }

    fun register(email: String, password: String) {
        viewModelScope.launch {
            try {
                authRepository.register(email, password)
                _authResult.value = AuthResult(success = true)
            } catch (e: Exception) {
                _authResult.value = AuthResult(success = false, errorMessage = e.message)
            }
        }
    }

    fun clearAuthResults() {
        _authResult.value = null
    }
}
